<template>
  <el-card class="form-container" shadow="never">
    <el-tree
        :data="menuTreeList"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="treeRef"
        highlight-current
        :props="defaultProps"
    />
    <div style="margin-top: 20px" align="center">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button @click="handleClear">清空</el-button>
    </div>
  </el-card>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {ElMessage, ElMessageBox} from 'element-plus';
import {fetchTreeList} from '@/api/menu';
import {listMenuByRole,allocMenu} from '@/api/role';

const route = useRoute();
const router = useRouter();
const treeRef = ref(null);
const menuTreeList = ref([]);
const defaultProps = {
  children: 'children',
  label: 'title'
};
const roleId = ref(null);

// 获取菜单树
const treeList = async () => {
  try {
    const response = await fetchTreeList();
    menuTreeList.value = response.data.data;
  } catch (error) {
    console.error('Error fetching menu tree:', error);
    ElMessage({
      message: '获取菜单树失败，请重试',
      type: 'error',
      duration: 1000
    });
  }
};

// 根据角色获取已分配的菜单
const getRoleMenu = async (roleIdValue) => {
  try {
    const response = await listMenuByRole(roleIdValue);
    let menuList = response.data.data || [];
    let checkedMenuIds = menuList.filter(menu => menu.parentId !== 0).map(menu => menu.id);
    treeRef.value?.setCheckedKeys(checkedMenuIds);
  } catch (error) {
    console.error('Error fetching role menus:', error);
    ElMessage({
      message: '获取角色菜单失败，请重试',
      type: 'error',
      duration: 1000
    });
  }
};

// 保存菜单分配
const handleSave = async () => {
  try {
    await ElMessageBox.confirm('是否分配菜单？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    let checkedNodes = treeRef.value?.getCheckedNodes() || [];
    let checkedMenuIds = new Set();

    checkedNodes.forEach(checkedNode => {
      checkedMenuIds.add(checkedNode.id);
      if (checkedNode.parentId !== 0) {
        checkedMenuIds.add(checkedNode.parentId);
      }
    });

    const params = new URLSearchParams();
    params.append("roleId", roleId.value);
    params.append("menuIds", Array.from(checkedMenuIds));

    await allocMenu(params);
    ElMessage({
      message: '分配成功',
      type: 'success',
      duration: 1000
    });
    router.back();
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('Error allocating menu:', error);
      ElMessage({
        message: '分配菜单失败，请重试',
        type: 'error',
        duration: 1000
      });
    }
  }
};

// 清空选中项
const handleClear = () => {
  treeRef.value?.setCheckedKeys([]);
};

onMounted(() => {
  roleId.value = route.query.roleId;
  treeList();
  getRoleMenu(roleId.value);
});
</script>

<style scoped>
/* Your styles here */
</style>